package nachos.threads;
import nachos.machine.*;
import static java.lang.Math.sqrt;

public class DeterPrime implements Runnable   //Determines if a number is prime or not
{
    public DeterPrime(int l, int u, int[] c)  //constructor
	{
		lower = l; 
		upper = u; 
		count = new int[1];
		count[0] = c[0];
	}
	
    public boolean isPrime(int number) //function to determine prime numbers
	{
	  if(number < 0)		//if negative, not prime
	        return false;
	  if (number == 1)		//1 is not prime
            return false;
      if (number == 2)		//2 is prime
            return true;
      if (number % 2 == 0)	//even numbers are prime
            return false;
      for (int d = 3; d <= (int) sqrt(number); d++)	//only have to check up to the square root of the number
            if (number % d == 0)	//if it is divisible by any number, not prime
                  return false;
      return true;		//if it passed all the tests, then it is prime
    }
	
	public void run()
	{
		++count[0];		//increase the thread count by 1
		while(lower < upper)   //for each number in the range... see if it is prime (range is small, 5 or less)
		{
			if(isPrime(lower))
				System.out.println(lower + " is prime.");
			else
				System.out.println(lower + " is not prime.");
			++lower;
		}
		--count[0];		//decrease the thread count by 1
	}
 	
	private int lower;
	private int upper;
	private int[] count;
}
